<template>
  <div class="patient-info-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">患者信息</span>
          <div class="toolbar">
            <el-input
                v-model="searchQuery"
                placeholder="搜索年龄、性别、出生日期、诊断年龄"
                :prefix-icon="Search"
                style="width: 350px;"
                clearable
                @input="handleSearch"
            />
          </div>
        </div>
      </template>

      <el-table
          v-loading="loading"
          :data="pagedPatients"
          stripe
          border
          style="width: 100%;"
          height="calc(100vh - 280px)"
          class="custom-table"
      >
        <el-table-column prop="name" label="姓名" width="120" align="center" />
        <el-table-column prop="phone" label="手机号" width="150" align="center" />
        <el-table-column prop="age" label="年龄" width="100" align="center" sortable />
        <el-table-column prop="gender" label="性别" width="100" align="center" />
        <el-table-column prop="birthDate" label="出生日期" width="160" align="center" sortable>
          <template #default="{ row }">
            {{ formatBirthDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="diagnoseAge" label="诊断年龄" width="120" align="center" sortable />
        <el-table-column prop="allergyInfo" label="过敏史" min-width="180" show-overflow-tooltip />
        <el-table-column prop="medicalHistory" label="既往病史" min-width="180" show-overflow-tooltip />
        <el-table-column prop="contactPhone" label="联系电话" width="150" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />

        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="viewPatientSymptoms(scope.row.id)" >
              查看症状/不良反应
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-footer">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredPatients.length"
            background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router' // 导入 useRouter

// --- 数据定义 ---
const patients = ref([])
const loading = ref(true)
const searchQuery = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

const router = useRouter() // 获取路由器实例

// --- 方法 ---

// 获取患者信息
const fetchPatients = async () => {
  loading.value = true
  try {
    // 假设 userdetail/listAll 接口能返回所有用户（包括user表和user_detail表合并的字段）
    // 如果 /userdetail/listAll 接口只返回 user_detail 的字段，
    // 你可能需要先获取所有 user 的列表，再逐个获取 user_detail 或调整后端接口
    const res = await axios.get('http://localhost:8080/userdetail/listAll')
    const list = res.data.data?.data
    patients.value = Array.isArray(list) ? list : []
    ElMessage.success('患者信息获取成功！')
  } catch (error) {
    console.error('获取患者信息失败', error)
    ElMessage.error('获取患者信息失败，请检查网络或服务器。')
  } finally {
    loading.value = false
  }
}

// 日期格式化函数
const formatBirthDate = (dateString) => {
  if (!dateString) return ''
  return dateString
}

// 搜索处理函数
const handleSearch = () => {
  currentPage.value = 1
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 前端搜索过滤
const filteredPatients = computed(() => {
  if (!searchQuery.value) return patients.value

  const q = searchQuery.value.toLowerCase().trim()
  return patients.value.filter((p) => {
    // 确保 patient 对象有这些属性，或者添加默认值以避免 undefined 错误
    const nameStr = String(p.name || '').toLowerCase(); // 新增：姓名搜索
    const phoneStr = String(p.phone || '').toLowerCase(); // 新增：手机号搜索

    const ageStr = String(p.age || '').toLowerCase();
    const genderStr = String(p.gender || '').toLowerCase();
    const birthDateStr = String(p.birthDate || '').toLowerCase();
    const diagnoseAgeStr = String(p.diagnoseAge || '').toLowerCase();
    const allergyInfoStr = String(p.allergyInfo || '').toLowerCase();
    const medicalHistoryStr = String(p.medicalHistory || '').toLowerCase();
    const contactPhoneStr = String(p.contactPhone || '').toLowerCase(); // 拼写修正
    const addressStr = String(p.address || '').toLowerCase();

    return nameStr.includes(q) || // 允许搜索姓名
        phoneStr.includes(q) || // 允许搜索手机号
        ageStr.includes(q) ||
        genderStr.includes(q) ||
        birthDateStr.includes(q) ||
        diagnoseAgeStr.includes(q) ||
        allergyInfoStr.includes(q) ||
        medicalHistoryStr.includes(q) ||
        contactPhoneStr.includes(q) ||
        addressStr.includes(q);
  })
})

// 应用分页的患者数据
const pagedPatients = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPatients.value.slice(start, end)
})

// 跳转到查看患者症状和不良反应页面
const viewPatientSymptoms = (patientId) => {
  router.push({
    path: '/home/symptoms',
    query: { patientId: patientId } // 通过查询参数传递 patientId
  });
}

// --- 生命周期钩子 ---
onMounted(() => {
  fetchPatients()
})
</script>

<style scoped>
.patient-info-container {
  padding: 30px;
  background-color: #f8fbfd;
  min-height: calc(100vh - 60px);
}

.box-card {
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.card-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.toolbar .el-input {
  max-width: 400px;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.custom-table :deep(.el-table__header-wrapper th) {
  background-color: #f2f6fc;
  color: #555;
  font-weight: 600;
  padding: 12px 0;
}

.custom-table :deep(.el-table__cell) {
  padding: 10px 0;
}

.pagination-footer {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-pagination {
  padding: 5px 0;
}
</style>